package br.com.trumah.dao.impl;

import java.util.List;

import org.eclipse.jdt.internal.compiler.flow.FinallyFlowContext;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import br.com.trumah.dao.interfaces.BeneficioDAO;
import br.com.trumah.model.Beneficio;
import br.com.trumah.utils.HibernateUtil;

public class BeneficioDAOImpl implements BeneficioDAO {

	
	private Session session = null;
	private Transaction t = null;
	
	
	@Override
	public void salvar(Beneficio beneficio) {

		try {
			
			session = HibernateUtil.getSessionFactory().openSession();
			t = session.beginTransaction();
			session.save(beneficio);
			t.commit();
			
		} catch (HibernateException ex) {
			
			t.rollback();
			ex.printStackTrace();
			
		} finally {
			
			session.close();
			
		}
		
	}

	@Override
	public Beneficio obterBeneficio(long id) {

		Beneficio beneficio = null;
		
		try {

			session = HibernateUtil.getSessionFactory().openSession();
			beneficio = (Beneficio) session.load(Beneficio.class, id);
			
		} catch (HibernateException ex) {
			
			ex.printStackTrace();
			
		} finally {
			
			session.close();
			
		}
		
		return beneficio;
		
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Beneficio> listar() {
		
		List<Beneficio> lista = null;
		
		try {

			session = HibernateUtil.getSessionFactory().openSession();
			t = session.beginTransaction();
			lista = session.createQuery("from Beneficio").list();
			t.commit();
			
		} catch (HibernateException ex) {
			
			t.rollback();
			ex.printStackTrace();
			
		} finally {
			
			session.close();
			
		}
		
		return lista;
		
	}

	@Override
	public void remover(Beneficio beneficio) {

		try {
			
			session = HibernateUtil.getSessionFactory().openSession();
			t = session.beginTransaction();
			session.delete(beneficio);
			t.commit();
			
		} catch (HibernateException ex) {
			
			t.rollback();
			ex.printStackTrace();
			
		} finally {
			
			session.close();
			
		}
		
	}

	@Override
	public void atualizar(Beneficio beneficio) {
		
		try {
			
			session = HibernateUtil.getSessionFactory().openSession();
			t = session.beginTransaction();
			session.update(beneficio);
			t.commit();
			
			
		} catch (HibernateException ex) {
			
			t.rollback();
			ex.printStackTrace();
			
		} finally {
			
			session.close();
			
		}

	}

}
